package com.lw.thread;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author LW
 * @2020/8/18 15:45
 */
//测试Lock锁     ReetrantLock类实现了Lock接口
public class TestLock {

    public static void main(String[] args) {
        TestLock2 testLock2 = new TestLock2();
        new Thread(testLock2,"a").start();
        new Thread(testLock2,"b").start();
        new Thread(testLock2,"c").start();


    }

}

class TestLock2 implements Runnable{

    int ticketNums=10;
    //定义Lock锁   ReentrantLock可重入锁
    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true){

            try{//显示锁（手动开关  别忘了关）
                lock.lock();//加锁    Lock只有代码块锁
                if (ticketNums>0){
                    //synchronized是隐式锁（出了作用域自动释放）
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+ticketNums--);
                }else {
                    break;
                }
            }finally {
                lock.unlock();//解锁
            }

        }
    }
}